<template>
	<view>
		<view class="pay">
			<view class="part-one part">
				<view class="part-title"> 选择预约用车时间 </view>
				<view class="part-time">
					<view class="part-input">
						{{ handleTime | setTimeText }}
					</view>
				</view>
				<view class="part-tips">
					<view class="tips-title"> 超时文字说明 </view>
					<view class="tips-text"> 包车套餐，涵盖了套餐内的限定时间和限定里程实际用车，若超出套餐包含的时长或里程，将算作超套：超套部分的收费，将按照专车包车的计价规则，额外结算。 </view>
				</view>
			</view>
			<view class="part-two part">
				<view class="part-title"> 补充说明 </view>
				<u-gap height="20"></u-gap>
				<u-input placeholder-style="color: #999999;font-size: 28upx;" border-color="#DCDCDC"
					placeholder="请您输入您所需要补充的说明内容" type="textarea" :border="true" :height="198" :auto-height="true" />
			</view>
			<view class="agreement flex-verticality" @click="handleAgree">
				<image class="agreement-icon"
					:src="isAgree ? '../../static/pay/checked-yes.png' : '../../static/pay/checked-no.png'" mode=""></image>
				<text>我已阅读</text>
				<text style="color: #2884ff">《预约包车》</text>
				<text>相关协议说明。</text>
			</view>
		</view>
		<!--最底下按钮-->
		<view class="flex bottom-fix">
			<view class="cu-bar bg-white half-width">
				<view class="item-width-1">
					<text class="font-28-333333" style="margin-right: 20upx">需支付总金额</text>
					<text class="text-sm text-orange2">¥</text>
					<text class="text-lg text-orange2">{{ price | setPrice }}</text>
				</view>
			</view>
			<view class="cu-bar bg-gradual-orange submit-btn justify-center" @click="handlePay">立即支付</view>
		</view>
		<!-- 提示 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	var that;
	import {
		mapState
	} from "vuex";
	import md5 from "js-md5";
	export default {
		computed: {
			...mapState(["serviceType", "price", "startAddress", "endAddress", "handleTime", "charterCarForm",
				"specialCarForm", "flightNo", "lineId", "carlevel", "cityCode"
			]),
		},
		filters: {
			setPrice(price) {
				if (price) {
					return price.toFixed(2);
				}
			},
			setTimeText(time) {
				if (time) {
					var nowDateVal = new Date();
					var nD = nowDateVal.getDay();
					var dateVal = `${time}:00`.replace(/-/g, "/");
					var timeStamp = new Date(dateVal);
					var M = timeStamp.getMonth() + 1;
					var D = timeStamp.getDate();
					var h = timeStamp.getHours() < 10 ? "0" + timeStamp.getHours() : timeStamp.getHours();
					var m = timeStamp.getMinutes() < 10 ? "0" + timeStamp.getMinutes() : timeStamp.getMinutes();
					var w = timeStamp.getDay();
					var week; //星期
					const weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; //星期
					week = weeks[w];
					if (w - nD == 0) {
						week = "今天";
					} else if (w - nD == 1) {
						week = "明天";
					}
					return `${M}-${D} ${week} ${h}:${m}`;
				}
			},
		},
		onLoad() {
			that = this;
		},
		data() {
			return {
				isAgree: false,
				buttonFlag: true,
			};
		},
		methods: {
			handlePay() {
				if (!this.isAgree) {
					this.$refs.uToast.show({
						title: "请阅读并勾选相关协议",
						type: "warning",
						icon: false,
					});
					return;
				}
				if (this.buttonFlag) {
					this.buttonFlag = false;
					setTimeout(function() {
						that.buttonFlag = true;
					}, 1000);
					if (this.serviceType == 2) {
						// 2就是包车
						// this.charterCarPay();
						this.specialCarPay();
					} else {
						this.specialCarPay();
					}
				}
			},
			charterCarPay() {
				// this.$u
				//   .post("/orderManager/add", {
				//     serviceType: this.serviceType,
				//     localPhone: uni.getStorageSync("FF_USER_INFO").mobPhone,
				//     name: uni.getStorageSync("FF_USER_INFO").nickname,
				//     payPrice: this.price,
				//     handlerTime: this.handleTime + ":00",
				//     startAddr: this.startAddress.address,
				//     startLatitude: this.startAddress.latitude,
				//     startLongitude: this.startAddress.longitude,
				//     charterId: this.charterCarForm.id,
				//     carlevel: this.carlevel,
				//     cityCode: this.cityCode,
				//   })
				//   .then((data) => {
				//     that.userPay(data);
				//   });
			},
			specialCarPay() {
				console.log('this.spec11ialCa1rForm',this.specialCarForm);
				let form = {
					// priceMark: this.specialCarForm.priceMark,
					estimateId: this.specialCarForm.estimateId,
					vehicleType: this.specialCarForm.vehicleTypeId,
					inviteCode:uni.getStorageSync('inviteCode'),
					passengerInfo: {
						name: uni.getStorageSync('userName'),
						phone: uni.getStorageSync('FF_USER_INFO').phone,
					},
				};
				if(this.specialCarForm.days){
					form.days = this.specialCarForm.days
				}
				if(this.specialCarForm.dayPackageInfo){
					form.dailyDuration = this.specialCarForm.dayPackageInfo.dailyDuration
					form.dailyDistance = this.specialCarForm.dayPackageInfo.dailyDistance
				}
				
				if (!uni.getStorageSync('userName')) {
					uni.showModal({
						title: '请输入乘客姓名',
						content: '',
						editable: true, //是否显示输入框
						placeholderText: '请输入', //输入框提示内容
						confirmText: '确认',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								uni.setStorageSync('userName', res.content);
								form.passengerInfo.name = res.content
								this.$u.post("/vehicleService/order/create", form).then(res => {
									that.userPay(res.result);
								});
							}
						}
					});
				} else {
					this.$u.post("/vehicleService/order/create", form).then(res => {
						console.log('rererere',res);
						that.userPay(res.result);
					});
				}
				// this.$u
				//   .post("/orderManager/add", {
				//     serviceType: this.serviceType,
				//     localPhone: uni.getStorageSync("FF_USER_INFO").mobPhone,
				//     name: uni.getStorageSync("FF_USER_INFO").nickname,
				//     payPrice: this.price,
				//     handlerTime: this.handleTime + ":00",
				//     startAddr: this.startAddress.address,
				//     startLatitude: this.startAddress.latitude,
				//     startLongitude: this.startAddress.longitude,
				//     endAddr: this.endAddress.address,
				//     endLatitude: this.endAddress.latitude,
				//     endLongitude: this.endAddress.longitude,
				//     flightNumber: this.flightNo ? this.flightNo : "",
				//     lineId: this.lineId ? this.lineId : "",
				//     carlevel: this.carlevel,
				//     cityCode: this.cityCode,
				//     driverTotalPrice: this.specialCarForm.driverTotalPrice,
				//   })
				//   .then((data) => {
				//     that.userPay(data);
				//   });
			},
			handleAgree() {
				this.isAgree = !this.isAgree;
			},
			// 小程序支付，H5支付，公众号支付 小程序appid：wx3124d10594f60ef0 公众号appid： wx62978b36ba1a8de8
			async userPay(orderInfo) {
				console.log('orderInfo', orderInfo);
				let timeStamp = parseInt(Date.now() / 1000) + "";
				let packageId = "prepay_id=" + orderInfo.prepayId;
				let nonce_str = Math.random().toString(32).substr(0, 31);
				let signType = "MD5";
				const appid = uni.getAccountInfoSync().miniProgram.appId;

				// let payInfo =
				// 	`appId=${appid}&nonceStr=${nonce_str}&package=${packageId}&signType=${signType}&timeStamp=${timeStamp}`;
				// console.log('M44444444444444444',md5(payInfo));
				// let {data} = await this.$u.post("/wx/pay/genSign", {payInfo})
				// console.log('DDD',data);
				uni.requestPayment({
					timeStamp: orderInfo.timeStamp, //当前时间戳
					nonceStr: orderInfo.nonceStr, //随机字符串
					package: orderInfo.prepayId,
					signType: orderInfo.signType,
					paySign: orderInfo.paySign,
					success: function(res) {
						console.log("支付成功", res);
						that.$refs.uToast.show({
							title: "预约成功，正在跳转页面",
							type: "success",
							icon: false,
						});
						setTimeout(function() {
							uni.redirectTo({
								url: "../result/index",
							});
						}, 500);
					},
					fail: function(err) {
						console.log("支付失败", err);
						that.$refs.uToast.show({
							title: "支付失败",
							type: "error",
							icon: false,
						});
						setTimeout(function() {
							uni.reLaunch({
								url: "../order/index",
							});
						}, 500);
					},
				});
				// this.$u.post(`/pay/pay/${orderId}`, {
				//     openid: uni.getStorageSync("OPENID"),
				//   }).then((data) => {
				//     uni.requestPayment({
				//       timeStamp: data.timeStamp,
				//       nonceStr: data.nonceStr,
				//       package: data.packageValue,
				//       signType: data.signType,
				//       paySign: data.paySign,
				//       success: function (res) {
				//         that.$refs.uToast.show({
				//           title: "预约成功，正在跳转页面",
				//           type: "success",
				//           icon: false,
				//         });
				//         setTimeout(function () {
				//           uni.redirectTo({
				//             url: "../result/index",
				//           });
				//         }, 500);
				//       },
				//       fail: function (err) {
				//         that.$refs.uToast.show({
				//           title: "支付失败",
				//           type: "error",
				//           icon: false,
				//         });
				//         setTimeout(function () {
				//           uni.reLaunch({
				//             url: "../order/index",
				//           });
				//         }, 500);
				//       },
				//     });
				//   });
			},
		},
	};
</script>

<style lang="scss">
	page {
		background-color: #f7f7f7;
		line-height: 1;
	}

	.pay {
		padding: 34upx 30upx;

		.part {
			background: #ffffff;
			box-shadow: 0px 0px 20upx 0px rgba(0, 0, 0, 0.08);
			border-radius: 10upx;
		}

		.part-one {
			padding: 46upx 34upx 36upx 34upx;

			.part-tips {
				margin-top: 20upx;
				padding: 26upx 20upx 38upx 20upx;
				border: 2upx dashed #dcdcdc;
				border-radius: 10upx;

				.tips-title {
					font-size: 28upx;
					color: #333333;
					margin-bottom: 20upx;
				}

				.tips-text {
					font-size: 24upx;
					color: #666666;
					line-height: 32upx;
					text-align: justify;
				}
			}

			.part-time {
				background: #f7f7f7;
				border-radius: 10upx;
				padding: 18upx 33upx;
				margin-top: 20upx;
			}

			.part-input {
				font-size: 30upx;
				color: #333333;
			}

			.part-placeholder {
				font-size: 30upx;
				color: #999999;
			}
		}

		.part-two {
			padding: 54upx 34upx 46upx 34upx;
			margin-top: 20upx;
		}

		.part-title {
			font-size: 32upx;
			font-weight: bold;
			color: #333333;
		}

		.agreement {
			font-size: 26upx;
			color: #666666;
			margin-top: 20upx;

			.agreement-icon {
				width: 28upx;
				height: 28upx;
				margin-right: 16upx;
			}
		}
	}

	/* 费用明细模态框 */
	.flex {
		display: flex;
	}

	.justify-center {
		justify-content: center;
	}

	.cu-bar {
		display: flex;
		align-items: center;
		min-height: 98upx;
		justify-content: space-between;
	}

	.submit-btn {
		width: 300upx;
		justify-content: center;
		font-size: 36upx;
		font-weight: bold;
	}

	.text-orange2 {
		color: #ff4e18;
	}

	.bg-white {
		background-color: #ffffff;
		color: #808080;
	}

	.bottom-fix {
		position: fixed;
		bottom: 0px;
		width: 100%;
		box-shadow: 0px 0px 20upx 0px rgba(0, 0, 0, 0.08);
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容 iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容 iOS >= 11.2 */
		background-color: #ffffff;
	}

	.half-width {
		flex: 1;
		padding: 0 30upx;
	}

	.text-sm {
		font-size: 22upx;
		margin-right: 10upx;
	}

	.text-lg {
		font-size: 36upx;
		font-weight: bold;
		margin-left: 5upx;
	}

	.bg-gradual-orange {
		background: #178dff;
		color: #ffffff;
	}

	.font-28-333333 {
		color: #333333;
		font-size: 28upx;
	}
</style>